"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""

import os
import cv2
import string
import ctypes
from datetime import datetime


# 获取剩余空间
def get_free_space(path):
    free_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes))
    return free_bytes


# 1、创建VideoCapture的对象cap，并对视频的width*high设置
cap1 = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
cap2 = cv2.VideoCapture(1 + cv2.CAP_DSHOW)
cap3 = cv2.VideoCapture(2 + cv2.CAP_DSHOW)

cap1.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap1.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

cap2.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap2.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

cap3.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap3.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# 2、获取当前时间，以及设定容量剩余限制，如果低于容量限制则切换盘符
drive_letter = None
threshold = 17867000000
now = datetime.now()
now_time = now.strftime("%Y-%m-%d %H-%M-%S")
available_drives = ['%s:' % d for d in reversed(string.ascii_uppercase) if os.path.exists('%s:' % d)]
print(f'available_drives = {available_drives}')

for drive in available_drives:
    rem_space = get_free_space(drive).value
    if rem_space >= threshold:
        drive_letter = drive
        print(f'drive_letter is {drive_letter}')
        break
    

if drive_letter is not None:
    folder_path = f'{drive_letter}/video'
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    video_path1 = f'{folder_path}/{now_time}-frame1.avi'
    video_path2 = f'{folder_path}/{now_time}-frame2.avi'
    video_path3 = f'{folder_path}/{now_time}-frane3.avi'
else:
    video_path1 = None
    video_path2 = None
    video_path3 = None
# 3、生成fourcc code，设定编码格式
fourcc = cv2.VideoWriter_fourcc('I', '4', '2', '0')

# 4、需要保存，创建VideoWriter对象out
out1 = cv2.VideoWriter(video_path1, fourcc, 30.0, (640, 480))
out2 = cv2.VideoWriter(video_path2, fourcc, 30.0, (640, 480))
out3 = cv2.VideoWriter(video_path3, fourcc, 30.0, (640, 480))

# 5、确保cap打开了
while True:
    if not cap1.isOpened():
        print("cap1 is not opened, open the cap1")
        cap1.open()
    elif not cap2.isOpened():
        print("cap2 is not opened, open2 the cap")
        cap2.open()
    elif not cap3.isOpened():
        print("cap3 is not opened, open3 the cap")
        cap2.open()
    else:
        print('cap1/2/3 is opened, read the video stream...')
        break

# 6、使用一个While循环不间断地对usb摄像头进行读取，一直到遇到键盘终止事件时break掉
if video_path1 is not None:
    while True:
        # 使用cap.read()从摄像头读取一帧
        ret1, frame1 = cap1.read()
        ret2, frame2 = cap2.read()
        ret3, frame3 = cap3.read()

        frame1 = cv2.flip(frame1, 1)
        frame2 = cv2.flip(frame2, 1)
        frame3 = cv2.flip(frame3, 1)

        try:
            out1.write(frame1)
            out2.write(frame2)
            out3.write(frame3)
            
        except Exception as e:
            print(f"Failed to save video: {str(e)}")

        # cv2.imshow('frame1', frame1)
        # cv2.imshow('frame2', frame2)
        # cv2.imshow('frame3', frame3)

        if cv2.waitKey(1) == ord('q'):
            break

    cap1.release()
    cap2.release()
    cap3.release()
    print('release cap')
    out1.release()
    out2.release()
    out3.release()
    print('release writer')
    cv2.destroyAllWindows()
    print('release all windows')
else:
    pass

